<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.userName" placeholder="请输入用户名" style="width: 200px" class="filter-item" />
      <!-- <el-select v-model="listQuery.department" placeholder="请选择所属单位" clearable style="width: 200px;"
        class="filter-item">
        <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="success" @click="createUser">
        创建账号
      </el-button>
    </div>
    <div class="block block-regular">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="calc(85vh - 155px)">
        <el-table-column label="序号" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ (listQuery.page - 1) * listQuery.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userName" align="center" label="用户名" />
        <el-table-column prop="roleName" align="center" label="角色" />
        <el-table-column label="操作" align="center" min-width="180">
          <template slot-scope="scope">
            <!-- <el-button size="medium" type="primary" @click="HandleChangeRole(scope.row)">设置角色</el-button> -->
            <el-button size="medium" type="warning" @click="updateUserInfo(scope.row)">修改信息</el-button>
            <el-button size="medium" type="danger" @click="delUser(scope.row.userId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination background layout="total, sizes, prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="pageSize" :page-sizes="[10, 50, 100, 200, 500]" :total="total" :current-page="currentPage" align="center"></el-pagination>
    <el-dialog v-if="listQuery.isRegular == 1" :title="formTextMap[formOperationType]" :visible.sync="userDialogFormVisible" :modal="true" custom-class="ly-running-info-body" @close="createUserDialogClosed" class="view-dialog" :show-close="false">
      <el-form ref="userForm" :model="userForm" label-width="40%" style="width:60%;" :rules="rules">
        <el-form-item label="用户名:" key="personName1" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item label="角色:" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色" style="width: 60%;">
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属车站:" key="stationIds1" prop="stationIds">
          <el-select v-model="userForm.stationIds" multiple placeholder="请选择" style="width: 100%;" @change="stationChanged">
            <el-option v-for="station in stationNames" :key="station.stationNum" :label="station.stationName" :value="station.stationNum"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="55%">
          <el-button v-if="formOperationType == 'edit'" type="danger" @click="resetPassword">重置密码</el-button>
          <el-button v-if="formOperationType == 'create'" type="primary" @click="addUserSubmit">立即创建</el-button>
          <el-button v-else type="primary" @click.native="updateUserSubmit">确定修改</el-button>
          <el-button @click="createUserDialogClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-if="listQuery.isRegular == 0" :title="formTextMap[formOperationType]" :visible.sync="userDialogFormVisible" :modal="true" custom-class="ly-running-info-body" @close="createUserDialogClosed" class="view-dialog" :show-close="false">
      <el-form ref="userForm" :model="userForm" label-width="40%" style="width:60%;" :rules="rules0">
        <el-form-item key="userName0" label="手机号:" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <!-- <el-form-item v-if="formOperationType == 'create'" label="密码：" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item v-if="formOperationType == 'create'" label="确认密码：" prop="password1">
          <el-input v-model="userForm.password1" placeholder="请再次输入密码" show-password />
        </el-form-item> -->
        <el-form-item label="用户名:" prop="userName" key="personName0">
          <el-input v-model="userForm.userName" />
        </el-form-item>

        <el-form-item label="所属车站:" prop="stationIds" key="stationIds0">
          <el-select v-model="userForm.stationIds" multiple placeholder="请选择" style="width: 100%;" @change="stationChanged">
            <el-option v-for="station in stationNames" :key="station.stationNum" :label="station.stationName" :value="station.stationNum"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="55%">
          <el-button v-if="formOperationType == 'edit'" type="danger" @click="resetPassword">重置密码</el-button>
          <el-button v-if="formOperationType == 'create'" type="primary" @click="addUserSubmit">立即创建</el-button>
          <el-button v-else type="primary" @click.native="updateUserSubmit">确定修改</el-button>
          <el-button @click="createUserDialogClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getOptions, addOrUpdateOptions, getUserPageInfos, getPageInfoList, checkRegistered, deleteUser, createOrUpdate, resetPwd, updateUserRoles } from '@/api/user'
import { getRoles, getRoleOptions } from '@/api/role'
import Pagination from '@/components/Pagination'
import { setOrgOptions } from '../../memberOrgs'
import { updateMemberOrgs } from '@/api/organization'
import { getStationNames, addOrUpdateMemberStations } from '@/api/station'
import { cloneDeep } from 'lodash'

export default {
  components: { Pagination },
  data() {
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      }
      setTimeout(() => {
        if (this.userForm.userName == this.userNameBeforeChange) {
          callback()
        } else {
          checkRegistered(value).then(res => {
            if (res.code !== 0) {
              callback(new Error(res.msg))
            } else {
              callback()
            }
          })
        }
      }, 1000)
    }
    var checkphoneNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('临时员工手机号不能为空'))
      } else {
        callback()
      }
    }
    // var validatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入密码'));
    //   } else {
    //     if (this.userForm.password1 !== '') {
    //       this.$refs.userForm.validateField('password1');
    //     }
    //     callback();
    //   }
    // };
    // var validatePass2 = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请再次输入密码'));
    //   } else if (value !== this.userForm.password) {
    //     callback(new Error('两次输入密码不一致!'));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6 //如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      rules: {
        userName: [{ required: true, validator: checkUserName, trigger: 'blur' }],
        personName: [{ required: true, message: '员工姓名为必填项', trigger: 'blur' }],
        roleId: [{ required: true, message: '角色为必填项', trigger: 'blur' }],
        org: [{ required: true, message: '所属部门为必填项', trigger: 'blur' }],
        stationIds: [{ required: true, message: '所属车站为必填项', trigger: 'blur' }],
        jobTypeId: [{ required: true, message: '所属工种为必填项', trigger: 'blur' }]
        // taskTypeIds: [{ required: true, message: '所属任务类型为必填项', trigger: 'blur' }]
        // password: [
        //   { required: true, validator: validatePass, trigger: 'blur' }
        // ],
        // password1: [
        //   { required: true, validator: validatePass2, trigger: 'blur' }
        // ]
      },
      rules0: {
        userName: [{ required: true, validator: checkphoneNum, trigger: 'blur' }],
        personName: [{ required: true, message: '员工姓名为必填项', trigger: 'blur' }],
        roleId: [{ required: true, message: '角色为必填项', trigger: 'blur' }],
        department: [{ required: true, message: '部门名称为必填项', trigger: 'blur' }],
        stationIds: [{ required: true, message: '所属车站为必填项', trigger: 'blur' }],
        jobTypeId: [{ required: true, message: '所属工种为必填项', trigger: 'blur' }]
        // taskTypeIds: [{ required: true, message: '所属任务类型为必填项', trigger: 'blur' }]
      },
      taskTypeNames: [],
      roleOptions: [],
      stationNames: [],
      isStationChanged: false,
      userNameBeforeChange: '',
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      innerVisible: false,
      isOrgChanged: false,
      orgProps: {
        value: 'orgId', //匹配响应数据中的id
        label: 'orgName', //匹配响应数据中的name
        children: 'children', //匹配响应数据中的children
        checkStrictly: true
      },
      orgManageProps: {
        value: 'orgId', //匹配响应数据中的id
        label: 'orgName', //匹配响应数据中的name
        children: 'children', //匹配响应数据中的children
        multiple: true,
        checkStrictly: true
      },
      orgOptions: [],
      memberOrgForm: {
        memberId: 0,
        orgId: 0,
        memberType: 1
      },
      formOperationType: '',
      formTextMap: { create: '添加用户', edit: '修改用户' },
      nowUserName: {},
      checkedRole: [],
      roles: [],
      loading: true,
      tableData: [],
      total: 10,
      selectedRow: {},
      roleDialogFormVisible: false,
      listQuery: {
        userName: '',
        personName: '',
        job: '',
        isRegular: 1,
        page: 1,
        size: 10
      },
      total: 0,
      userDialogFormVisible: false,
      userForm: {
        department: '',
        userId: '',
        roleId: '',
        userName: '',
        introduction: '',
        gender: '',
        birthday: null,
        org: [],
        job: '',
        phoneNum: '',
        password: '123456',
        password1: '',
        isRegular: 1,
        email: '',
        personName: '',
        stationIds: [],
        jobTypeId: null,
        taskTypeIds: null
      },
      genderOptions: [
        {
          value: '男',
          label: '男'
        },
        {
          value: '女',
          label: '女'
        }
      ],
      jobOptions: []
    }
  },
  computed: {
    showOrgManage() {
      let arr = this.$store.getters.op_perm
      let isExist = arr.indexOf(21) !== -1
      return isExist
    },
    type1() {
      if (this.listQuery.isRegular == 1) {
        return 'primary'
      } else {
        return 'info'
      }
    },
    type0() {
      if (this.listQuery.isRegular == 0) {
        return 'primary'
      } else {
        return 'info'
      }
    }
  },
  created: function() {
    this.getRoleList()
    this.getRoleOptions()
    this.getList()
    this.getOption()
    this.getStationNameList()
    // this.getJobTypeNameList()
    // this.getTaskTypeNameList()
  },
  methods: {
    handleCurrentChange: function(currentPage) {
      this.listQuery.page = currentPage
      this.getList(this.listQuery)
    },
    handleSizeChange: function(size) {
      this.listQuery.size = size
      this.getList(this.listQuery)
    },

    userChanged(isRegular) {
      Object.keys(this.listQuery).forEach(key => {
        this.listQuery[key] = null
      })
      this.listQuery.isRegular = isRegular
      this.listQuery.page = 1
      this.listQuery.size = 10
      this.getList()
    },
    stationChanged(val) {
      console.log(val, this.userForm.stationIds, 'dff')
      this.userForm.stationIds = val
      this.$forceUpdate()
      this.isStationChanged = true
    },
    getStationNameList() {
      getStationNames().then(res => {
        var objArray = res.data
        if (this.$store.getters.roles != 1) {
          this.stationNames = objArray
        } else {
          var numberArray = this.$store.getters.stationIds
          if (numberArray.length != 0) {
            for (var i = 0; i < objArray.length; i++) {
              var obj = objArray[i]
              // 判断当前对象的 stationNum 是否在数组 numberArray 中
              // if (numberArray.indexOf(obj.stationNum) == -1) {
              //   // 将匹配的对象添加到新数组中
              //   obj.disabled = true
              // }
            }
          }
          this.stationNames = objArray
        }
      })
    },
    cancelAddOrUpdateJobs() {
      this.dynamicTags = this.jobOptions
      this.innerVisible = false
    },
    handleAddOrUpdateJobs() {
      var jobData = { optionName: '', optionJson: '' }
      jobData.optionName = 'jobs'
      jobData.optionJson = this.dynamicTags
      addOrUpdateOptions(jobData).then(res => {
        if (res.code == 0) {
          this.jobOptions = this.dynamicTags
          this.$message.success('职务信息更新成功！')
          this.innerVisible = false
        } else {
          this.dynamicTags = this.jobOptions //白改，没作用
          this.$message.error(res.msg)
        }
      })
    },
    showJobs() {
      this.innerVisible = true
      this.dynamicTags = this.jobOptions
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    getOption() {
      getOptions('jobs').then(res => {
        this.jobOptions = res.data
      })
    },
    orgChanged() {
      this.isOrgChanged = true
      // let data = this.$refs.tree.getCheckedNodes()[0].pathLabels.toString()
      // //用for循环遍历获取的数据,并把逗号裁掉
      // for (let i = 0; i < data.length; i++) {
      //   if (data[i] === ',') {
      //     data = data.replace(data[i], '/')
      //   }
      // }
      // this.userForm.department = data
    },
    getList: function() {
      // let that = this
      this.loading = true
      getPageInfoList(this.listQuery).then(res => {
        if (res.code == 0) {
          this.tableData = res.data.records

          this.total = res.data.total
          this.loading = false
        }
      })
    },

    getRoleList: function() {
      getRoles().then(res => {
        this.roles = res.data
      })
    },
    getRoleOptions: function() {
      getRoleOptions().then(res => {
        this.roleOptions = res.data
      })
    },
    handleFilter: function() {
      this.getList()
    },
    //编辑更新用户信息
    updateUserInfo: function(row) {
      // console.log('998880')

      // this.loading = true
      this.formOperationType = 'edit'
      this.userDialogFormVisible = true
      this.$nextTick(() => {
        // 弹框打开时初始化表单
        this.userForm = cloneDeep(row)
        if (this.userForm.jobType) {
          this.userForm.jobTypeId = this.userForm.jobType.jobTypeId
        }
        this.userNameBeforeChange = this.userForm.userName
        this.userForm.stationIds = JSON.parse(row.taskTypeIds)
      })
      // console.log(row, 'row')
      // console.log(JSON.parse(row.taskTypeIds), 'row.taskTypeIds')

      // this.loading = false
    },
    delUser: function(id) {
      var that = this
      that.loading = true
      this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUser(id).then(res => {
            if (res.code === 0) {
              // this.calcPage() // 20230224 删除时计算一下
              that.getList()
              that.$message.success('用户删除成功！')
            } else {
              that.$message.error(res.msg)
            }
            that.loading = false
          })
        })
        .catch(() => {
          that.loading = false
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    createUser: function() {
      var that = this
      that.loading = true
      that.formOperationType = 'create'
      that.userDialogFormVisible = true
      // var clonForm = {}
      that.$nextTick(() => {
        // 弹框打开时初始化表单
        Object.keys(this.userForm).forEach(key => {
          this.userForm[key] = null
        })
        this.userForm['isRegular'] = this.listQuery.isRegular
        this.userForm['password'] = '123456'
        this.userForm['birthday'] = '1970-01-01'
        this.userForm['taskTypeIds'] = []
        this.userForm.roleId = this.roleOptions[0].roleId
      })
      that.loading = false
    },
    addUserSubmit: function() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          const formData = this.userForm
          this.SubmitFormData(formData)
        }
      })
    },
    updateUserSubmit: function() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          const formData = this.userForm
          this.userForm.taskTypeIds = []
          this.SubmitFormData(formData)
        }
      })
    },
    SubmitFormData(formData) {
      createOrUpdate(formData).then(res => {
        if (res.data) {
          this.userForm.userId = res.data.userId
          if (this.isStationChanged) {
            let data = {
              stationIds: this.userForm.stationIds,
              memberId: this.userForm.userId,
              memberType: 1
            }
            addOrUpdateMemberStations(data).then(res => {
              if (res.code != 0) {
                this.$message.error(res.msg)
              }
            })
          }
          if (this.isOrgChanged) {
            this.memberOrgForm.memberId = this.userForm.userId
            this.memberOrgForm.memberType = 1
            this.memberOrgForm.orgId = this.userForm.org.slice(-1)[0]
            updateMemberOrgs(this.memberOrgForm).then(res => {
              if (res.code == 0) {
                this.$message.success('用户信息提交成功')
              } else {
                this.$message.error(res.msg)
              }
              this.getList()
              // Object.keys(this.userForm).forEach(key => {
              //   if (key !== 'isRegular' || key !== 'password' || key !== 'birthday') {
              //     this.userForm[key] = null
              //   }
              // })
              this.userDialogFormVisible = false
              this.isOrgChanged = false
            })
          } else {
            this.$message.success('用户信息提交成功')
            this.getList()
            // Object.keys(this.userForm).forEach(key => {
            //   if (key !== 'isRegular' || key !== 'password' || key !== 'birthday') {
            //     this.userForm[key] = null
            //   }
            // })
            this.userDialogFormVisible = false
          }
        }
      })
    },
    //dialogClosed 点击右上角x，关闭对话框则元素清空
    createUserDialogClosed() {
      // Object.keys(this.userForm).forEach(key => {
      //   if (key !== 'isRegular' || key !== 'password' || key !== 'birthday') {
      //     this.userForm[key] = null
      //   }
      // });
      this.userNameBeforeChange = ''
      this.$refs.userForm.clearValidate()
      this.userDialogFormVisible = false
    },
    HandleChangeRole(row) {
      this.checkedRole = row.roles
      this.selectedRow = row
      this.roleDialogFormVisible = true
      this.nowUserName = row.userName
    },
    handlecheckedRoleChange(value) {
      // console.log(this.checkedRole, value)
    },
    HandleRoleSubmit() {
      const rolestr = this.checkedRole.join()
      var formData = { userId: '', roles: '' }
      formData.userId = this.selectedRow.userId
      // var formData = this.selectedRow
      formData.roles = rolestr.split(',')

      updateUserRoles(formData).then(res => {
        if (res.code === 0) {
          this.$message.success('角色修改成功')
          this.getList()
          this.roleDialogFormVisible = false
        }
      })
    },
    resetPassword() {
      var that = this
      const formData = that.userForm
      const userId = formData.userId
      const password = '123456'
      this.$confirm('此操作将重置密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          resetPwd(userId, password).then(res => {
            if (res.code === 0) {
              that.$message.success('密码重置成功')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置密码'
          })
        })
    }
  }
}
</script>
<style scoped>
/deep/ .el-tabs .tab-label {
  color: red;
}

.block .el-range-separator {
  width: 24px;
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px;
  /*滚动条宽度*/
  height: 8px;
  /*滚动条高度*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 0px;
  /*滚动条的背景区域的圆角*/
  background-color: rgba(2, 29, 87, 1);
  /*滚动条的背景颜色*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-corner {
  background-color: rgba(2, 29, 87, 1);
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 4px;
  /*滚动条的圆角*/
  background-color: rgba(24, 144, 255, 0.5);
  /*滚动条的背景颜色*/
}

/* .el-table__body-wrapper {
  height: calc(100% - 60px) !important;
} */

.use-name {
  font-size: 1rem;
  font-weight: 700;
  color: #606266;
}

/* 弹窗 */
/* 改变高度弹窗位置*/
/deep/ .dialog-content .el-dialog__body {
  height: 40vh;
  overflow: auto;
}

/deep/ .view-dialog > .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #d0d0d0;
  max-height: calc(100%);
  max-width: calc(100%);
}

/deep/ .el-dialog .el-dialog__body {
  flex: 1;
  overflow: hidden auto;
  /* 隐藏水平滚动条，显示垂直滚动条 */
  /* overflow-y: scroll; 显示垂直滚动条 */
}

/deep/ .view-dialog > .el-dialog > .el-dialog__header {
  width: 100%;
  height: 54px;
  line-height: 54px;
  text-align: center;
  background: #f4f5f7;
  border-radius: 12px 12px 0px 0px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #252b3a;
  padding: 0 0 0 40px;
  padding-left: 0;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__footer {
  padding-left: 0;
  padding-right: 0;
  text-align: center;
}

/deep/ .dialog-form > .el-form-item {
  margin-bottom: 30px;
}

/deep/ .dialog-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner {
  width: 220px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #dcdee2;
  border-radius: 3px;
}

/deep/ .dialog-form > .el-form-item > .el-form-item__content > .el-select > .el-input > .el-input__inner {
  width: 220px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #dcdee2;
  border-radius: 3px;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__header > .el-dialog__headerbtn {
  top: 0;
}

/deep/ .view-dialog .el-form-item__content {
  width: 100%;
}
</style>
